package com.wsoft.bpm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.wsoft.bpm.entity.ActNoticeEntity;
import com.wsoft.bpm.service.IActNoticeService;
import com.wsoft.bpm.vo.NoticeVO;
import com.wsoft.core.cmd.DcConfigService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 提供给外部的知会接口
 *
 * @Author zhonglj
 * @Date 2025/1/13 10:41
 */
@Service("bpmNoticeService")
public class BpmNoticeService implements DcConfigService {
    @Resource
    private IActNoticeService noticeService;

    @Override
    public Long count(Map<String, Object> paramMap) {
        return Long.valueOf(CollUtil.size(noticeService.unReadList()));
    }

    @Override
    public List<NoticeVO> list(Map<String, Object> paramMap) {
        String title = MapUtil.getStr(paramMap, "title");
        LocalDateTime start = null;
        LocalDateTime end = null;
        Object createTimeObj = paramMap.get("createTime");
        if (createTimeObj != null && createTimeObj instanceof List) {
            List<String> createTimes = (List<String>) createTimeObj;
            if (CollUtil.isNotEmpty(createTimes)) {
                start = DateUtil.parseLocalDateTime(createTimes.get(0));
                end = DateUtil.parseLocalDateTime(createTimes.get(1));
            }
        }
        final LocalDateTime startTime = start;
        final LocalDateTime endTime = end;

        List<ActNoticeEntity> unReadList = noticeService.unReadList();
        List<NoticeVO> collect = noticeService.packageExtraNoticeData(unReadList);
        collect = collect.stream()
                .filter(vo -> {
                    if (StrUtil.isNotBlank(title)) {
                        if (!StrUtil.contains(vo.getTitle(), title)) {
                            return false;
                        }
                    }
                    if (startTime != null) {
                        if (!(startTime.compareTo(vo.getCreateTime()) <= 0)) {
                            return false;
                        }
                    }

                    if (endTime != null) {
                        LocalDateTime offset = LocalDateTimeUtil.offset(endTime, 1, ChronoUnit.DAYS);
                        if (!(offset.compareTo(vo.getCreateTime()) > 0)) {
                            return false;
                        }
                    }

                    return true;
                }).collect(Collectors.toList());
        return collect;
    }
}
